#include <iostream>
#include <vector>

using namespace std;

/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


class Solution {
public:
    vector<vector<int>> ans;

    void dfs(TreeNode* root, vector<int> &path, int cur, int targetSum){
        if (!root) {
            return;
        }  

        path.push_back(root->val);
        cur = cur + root->val;

        if (!root->left && !root->right && cur == targetSum) {
            ans.push_back(path);
            // 就算是得到了结果，也需要恢复现场。
            path.pop_back();
            cur -= root->val;
            return;
        }
        dfs(root->left, path, cur, targetSum);
        dfs(root->right, path, cur, targetSum);
        // 恢复现场
        cur -= root->val;
        path.pop_back();
    }

    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<int> path;
        dfs(root, path, 0, targetSum);

        return ans;
    }
};